import { defineStore } from "pinia";

interface IClassType {
  id: number;
  name: string;
  parentId: number;
  iconUrl: string;
  level: number;
  sort: string;
  visible: number;
  active: boolean;
  children: Array<IClassType>;
}
function setActiveList(list: Array<IClassType>) {
  let stateList: Array<IClassType>;
  if (list.length == 0) {
    stateList = [];
  } else {
    stateList = [...list].map((item) => {
      item["active"] = false;
      return item;
    });
    stateList[0].active = true;
  }
  return stateList;
}
// 你可以对 `defineStore()` 的返回值进行任意命名，但最好使用 store 的名字，同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`，`useCartStore`，`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useClassifyStore = defineStore("productClassify", {
  state: () => {
    return {
      firstList: [] as Array<IClassType>,
      secList: [] as Array<IClassType>,
      thirdList: [] as Array<IClassType>,
    };
  },
  getters: {
    getFirstList(): Array<IClassType> {
      return this.firstList;
    },
    getSecList(): Array<IClassType> {
      return this.secList;
    },
    getThirdList(): Array<IClassType> {
      return this.thirdList;
    },
  },
  actions: {
    setClassList(list: Array<IClassType>) {
      this.firstList = setActiveList(list);
      list = [...(this.firstList.length ? this.firstList[0].children : [])];
      this.secList = setActiveList(list);
      list = [...(this.secList.length ? this.secList[0].children : [])];
      this.thirdList = setActiveList(list);
    },

    activeItem(item: IClassType) {
      let list = [[...this.firstList], [...this.secList], [...this.thirdList]];
      list[item.level-1].forEach((ite) => {
        ite.active = false;
        if (ite.id == item.id) {
          ite.active = true;
					//修改子级菜单数据
					if(item.level>=2){
						//点击菜单为二三级
						if(ite.children.length > 0) {
							list[item.level] = setActiveList(ite.children);
						}else {
							list[item.level] = []
						}
					}else{
						//点击菜单为一级
						if(ite.children.length > 0) {
							list[item.level] = setActiveList(ite.children);
							//根据二级判断三级菜单
							if(list[item.level][0].children.length > 0) {
								list[item.level+1] = setActiveList(list[item.level][0].children);
							}else {
								list[item.level+1] = []
							}
						}else {
							list[item.level] = []
							list[item.level+1]=[]
						}
					}
        }
      });
      this.firstList = [...list[0]];
      this.secList = [...list[1]];
      this.thirdList = [...list[2]];
    },
  },
  //开启持久化
  persist: true,
});
